
class ParallelController {

    constructor(parallelCount = 2) {
        this.parallelCount = parallelCount
        this.runningCount = 0
        this.tasks = []
    }

    add(task) {
        return new Promise((resolve, reject) => {
            this.tasks.push({
                task,
                resolve,
                reject
            })

            this._run()
        })
    }

    _run() {
        while(this.tasks.length && this.runningCount < this.parallelCount) {
            let {task, resolve, reject} = this.tasks.shift()
            this.runningCount = this.runningCount + 1
            task()
                .then(resolve, reject)
                .finally(() => {
                    this.runningCount = this.runningCount - 1
                    this._run()
                })
        }
    }
}

const paralle = new ParallelController()
async function addTask(delay, name) {
    paralle.add(() => {
        return new Promise((resolve) => {
            setTimeout(() => {
                resolve()
            }, delay);
        })
    }).then(() => {
        console.log(`任务${name}完成`)
    })
}

addTask(9000, 1)
addTask(1000, 2)
addTask(4000, 3)
addTask(3000, 4)
addTask(5000, 5)
addTask(2000, 6)
